package carassius.GUI;

import carassius.DAL.AnimalRow;
import carassius.DAL.Database;
import java.awt.Window;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author siebz0r
 */
public class AnimalTable
		extends TableWithMenu
{
	private Window _parentWindow;

	public AnimalTable()
	{
		setTableHeader(null);
		DefaultTableModel model = new DefaultTableModel();
		model.addColumn("animalColumn");
		setModel(model);
	}

	public AnimalTable(Window parent)
	{
		super();
		_parentWindow = parent;
		setTableHeader(null);
		DefaultTableModel model = new DefaultTableModel();
		model.addColumn("animalColumn");
		setModel(model);
		TableColumn organismListColumn = getColumnModel().getColumn(0);
		AnimalTableCellProcessor animalTableCellProcessor = new AnimalTableCellProcessor(_parentWindow);
		organismListColumn.setCellRenderer(animalTableCellProcessor);
		organismListColumn.setCellEditor(animalTableCellProcessor);
	}

	@Override
	void add()
	{
		AnimalForm af = new AnimalForm(_parentWindow);
		af.setVisible(true);
	}

	@Override
	void remove()
	{
		if (getSelectedRow() != -1
				&& getValueAt(getSelectedRow(), 0) instanceof AnimalRow)
		{
			getCellEditor(getSelectedRow(), 0).cancelCellEditing();
			if (JOptionPane.showConfirmDialog(_parentWindow,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAnimal"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAnimalTitle"),
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION)
			{
				try
				{
					Database.getAnimalTable().delete((AnimalRow) getValueAt(getSelectedRow(), 0));
				}
				catch (SQLException ex)
				{
					ex.toString();
					JOptionPane.showMessageDialog(_parentWindow,
							ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAnimalError"),
							ResourceBundle.getBundle("carassius.resources.Messages").getString("DeleteAnimalErrorTitle"),
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}

	@Override
	void edit()
	{
		if (getSelectedRow() != -1
				&& getValueAt(getSelectedRow(), 0) instanceof AnimalRow)
		{
			AnimalForm af = new AnimalForm(_parentWindow, (AnimalRow) getValueAt(getSelectedRow(), 0));
			af.setVisible(true);
			getCellEditor(getSelectedRow(), 0).stopCellEditing();
		}
	}
}
